package demo.netty.netty.http.subcribe_server;

import demo.netty.netty.http.entity.SubscribeReq;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.serialization.ClassResolvers;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder;

public class NettySubReqClient {


    public static void main(String[] args) {
        int port = 8080;
        new NettySubReqClient().bind("127.0.0.1", 8080);
    }


    public void bind(String host, int port) {
        NioEventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap
                .group(group)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY, true)
                .handler(new ChildChannelHandler());
            ChannelFuture channelFuture = bootstrap.connect(host, port).sync();
            //等待服务端监听端口关闭
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            group.shutdownGracefully();
        }
    }


    private static class ChildChannelHandler extends ChannelInitializer<SocketChannel> {

        @Override
        protected void initChannel(SocketChannel socketChannel) throws Exception {
            //创建 WeakReferenceMap对类加载器进行缓存，支持多线程并发访问，当虚拟机内存不足时，会释放缓存中的内存，防止内存泄漏
            socketChannel.pipeline().addLast(
                new ObjectDecoder(1024,
                                  ClassResolvers.weakCachingConcurrentResolver(this.getClass().getClassLoader())));
            socketChannel.pipeline().addLast(new ObjectEncoder());
            socketChannel.pipeline().addLast(new SubReqClientHandler());
        }
    }


    private static class SubReqClientHandler extends SimpleChannelInboundHandler<Object> {

        @Override
        public void channelActive(ChannelHandlerContext ctx) throws Exception {
            for (int i = 0; i < 10; i++) {
                ctx.writeAndFlush(req(i));
            }
        }

        @Override
        public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
            System.out.println("Receive server response : [" + msg + "]");
        }

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            cause.printStackTrace();
            ctx.close();
        }

        private SubscribeReq req(int i) {
            SubscribeReq subscribeReq = new SubscribeReq();
            subscribeReq.setSubReqId(i);
            subscribeReq.setAddress("成都双流区");
            subscribeReq.setPhoneNumber("138xxxxxxx");
            subscribeReq.setProductName("Netty");
            subscribeReq.setUserName("Lilinfeng");
            return subscribeReq;
        }
    }



}
